package com.crp.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.crp.util.DigestUtil;

/**
 * @author jincongmin
 */
public class StatelessRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        // 仅支持StatelessToken类型的Token
        return token instanceof StatelessToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 根据用户名查找角色，请根据需求实现
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        StatelessToken statelessToken = (StatelessToken) token;
        String id = statelessToken.getKey();
        System.out.println("id:"+id);
        String secretkey = getKey(id);
        System.out.println("secretkey:"+secretkey);
        if (secretkey == null) {
            return null;
        }
        
        // 在服务器端生成客户端参数消息摘要
        String digest = DigestUtil.digest(secretkey, statelessToken.getParams());
        // 然后进行客户端消息摘要和服务器端消息摘要的匹配
        return new SimpleAuthenticationInfo(secretkey, digest.toUpperCase(), getName());
    }


    /**
     * 从缓存中获取secretKey
     *
     * @param key
     *
     * @return
     */
    private String getKey(String key) {
        //从缓存中获取
//        CacheUtil cacheUtil = CacheUtil.getInstance();
//        Object sk = cacheUtil.get(key);
//        if (sk != null) {
//            return (String)sk;
//        }
        return "123456";
    }
}
